
#include "zen_game_sprite.h"
#include "zen_game_activity.h"
#include <array>
#include "zen_game_digit.h"

namespace Zen
{
	namespace Game
	{
		static std::shared_ptr<Zen::Graphics::Buffer> CreateDigitBuffer()
		{
			std::vector<Point2> points = { { 0, 0 }, { 1, 0 }, { 0, 0.5 }, { 1, 0.5f }, { 0, 1 }, { 1, 1 } };
			auto buffer = Activity::Only()->GetGraphicsEngine()->GenerateBuffer();
			buffer->Initialize(sizeof(Point2) * points.size(), points.data());
			return buffer;
		}
		static std::vector<std::pair<size_t, size_t>> sIndexRange{};
		static std::shared_ptr<Zen::Graphics::IndexBuffer> CreateDigitIndexBuffer()
		{
			auto buffer = Activity::Only()->GetGraphicsEngine()->GenerateIndexBuffer();

			std::pair<int, int> indexs[] = { { 0, 1 }, { 0, 2 }, { 1, 3 }, { 2, 3 }, { 2, 4 }, { 3, 5 }, { 4, 5 }, { 1, 2 }, { 2, 5 } };
			auto count = std::size(indexs);

			std::vector<uint16_t> data;
			for (int value = 0; value < (1 << count); ++value)
			{
				std::vector<uint16_t> temp;
				std::vector<int> flags(count, 0);
				bool up{}, down{};
				for (int i = 0; i < count; ++i)
				{
					if ((value >> i) & 1)
					{
						auto& v = indexs[i];
						temp.push_back(v.first);
						temp.push_back(v.second);
					}
				}
				sIndexRange.push_back({ data.size(), temp.size() });
				data.insert(data.end(), temp.begin(), temp.end());
			}
			buffer->Initialize(data.size(), data.data());
			return buffer;
		}

		Zen::Game::Digit::Digit()
		{
			this->SetDrawMode(Zen::Graphics::EDrawMode::Line);
			static auto buffer = CreateDigitBuffer();
			SetPolygonBuffer(buffer, 2);
			static auto indexBuffer = CreateDigitIndexBuffer();
			SetIndexBuffer(indexBuffer);
			SetVertexDrawRange(0, 0);
		}
		void Digit::SetBitValue(int bits)
		{
			mBitValue = bits;
			auto v = sIndexRange.at((bits % (int)sIndexRange.size()));
			SetVertexDrawRange(v.first, v.second);
		}
		int Digit::GetBitValue() const
		{
			return mBitValue;
		}
	} // namespace Game
} // namespace Zen
